package com.wtwd.device.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.wtwd.device.util.Tools;
import com.wtwd.device.constant.Constants;
import com.wtwd.device.constant.RespCode;
import com.wtwd.device.model.entity.SysRole;
import com.wtwd.device.model.entity.SysUser;
import com.wtwd.device.model.entity.UserDto;
import com.wtwd.device.model.vo.RespEntity;
import com.wtwd.device.model.vo.UserInfoVo;
import com.wtwd.device.service.*;
import com.wtwd.device.utils.GetCurrentSysUserInfoUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author mjy
 * @date 2021/08/03
 * @description
 */
@Api(tags = "账号管理")
@RestController
@RequestMapping("/user")
public class SysUserController {

    private static final Logger logger = LoggerFactory.getLogger(SysUserController.class);
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RolePermissionService rolePermissionService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private GetCurrentSysUserInfoUtils getCurrentSysUserInfoUtils;
    @Autowired
    private AuthenticationService authenticationService;


    /**
     * 登录
     *
     * @param jsonObject
     * @return
     */

    @ApiOperation("登录")
    @DynamicParameters(name = "login", properties = {
            @DynamicParameter(name = "account", value = "账号名", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "password", value = "密码", dataTypeClass = String.class, required = true)
    })
    @PostMapping("/login")
    public RespEntity login(@RequestBody JSONObject jsonObject) {
        logger.info("login" + jsonObject);
        String account = jsonObject.getString("account");
        String password = jsonObject.getString("password");
        SysUser sysUser = sysUserService.getSysUserByAccount(account);
        Boolean checkLoginUser = sysUserService.checkLoginUser(sysUser, password);
        if (!checkLoginUser) {
            return new RespEntity(RespCode.USER_NAME_OR_PASSWORD_ERROR);
        }
        //构建token数据
        String token = Tools.getRamdomStr();
        redisService.createToken(sysUser, token);
        // 获取用户权限列表(获取所有权限列表,返回时注明是否有权)
        List<Map<String, Object>> userPermissionList = rolePermissionService.getRolePermissionList(sysUser.getRoleId());
        //构建返回值集合
        // 构建返回结果
        SysRole sysRole = sysRoleService.getSysRoleByRoleId(sysUser.getRoleId());
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("userPermissionList", userPermissionList);
        if (sysRole != null) {
            result.put("roleType", sysRole.getRoleType());
            result.put("roleNme", sysRole.getRoleName());
        }
        return new RespEntity(RespCode.SUCCESS, result);
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @PutMapping("/logout")
    public RespEntity logout(HttpServletRequest request) {
        logger.info("logout"+request);
        String token = request.getHeader(Constants.HEADER_TOKEN_KEY);
        redisService.delKey(token);
        return new RespEntity(RespCode.SUCCESS);
    }


    /**
     * 账户管理(只有管理员可见，查询所有账户)
     *
     * @param currentPage
     * @param pageSize
     * @param account
     * @return
     */
    @ApiOperation(value = "账户管理", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "当前页", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "pageSize", value = "页面大小", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "account", value = "账号名", required = false, dataTypeClass = String.class)
    })
    @GetMapping("/getSysUser")
    public RespEntity getSysUser(@RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage
            , @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize, @RequestParam(value = "account") String account) {
        logger.info("getSysUser param" + currentPage, pageSize, account);
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        RespEntity respEntity = authenticationService.checkAdmin(sysUser);
        if (respEntity != null) {
            return respEntity;
        }
        Page<Object> page = new Page<>(currentPage, pageSize);
        IPage<UserInfoVo> userInfoVos = sysUserService.getAllUserInfoByConditions(account, page);
        HashMap<String, Object> restMap = new HashMap<>();
        restMap.put("data", userInfoVos.getRecords());
        restMap.put("total", userInfoVos.getTotal());
        return new RespEntity(RespCode.SUCCESS, restMap);
    }


    /**
     * 添加账户(用户角色，只有超管可做,暂做限制)
     *
     * @param sysUserDto
     * @return
     */
    @ApiOperation(value = "添加账户", notes = "角色类型为客户时，客户id必传，否则不传")
    @DynamicParameters(name = "addSysUser", properties = {
            @DynamicParameter(name = "account", value = "账号名", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "password", value = "密码", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "roleId", value = "角色id", dataTypeClass = Long.class, required = true)
            , @DynamicParameter(name = "customerId", value = "客户id", dataTypeClass = String.class, required = false)
    })
    @PostMapping("addSysUser")
    public RespEntity addSysUser(@RequestBody UserDto sysUserDto) {
        logger.info("addSysUser param " + sysUserDto.toString());
        SysUser currentSysUserInfo = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        RespEntity respEntity = authenticationService.checkAdmin(currentSysUserInfo);
        if (respEntity != null) {
            return respEntity;
        }
        //鉴别用户,用户名是否重名
        SysUser user = sysUserService.getSysUserByAccount(sysUserDto.getAccount());
        if (user != null) {
            return new RespEntity(RespCode.USER_EXIST);
        }
        SysUser sysUser = new SysUser();
        sysUser.setCreateTime(new Date().getTime());
        sysUser.setUpdateTime(new Date().getTime());
        sysUser.setAccount(sysUserDto.getAccount());
        sysUser.setPassword(sysUserDto.getPassword());
        sysUser.setRoleId(sysUserDto.getRoleId());
        if (StringUtils.isBlank(sysUserDto.getCustomerId())) {
            sysUser.setCustomerId(0L);
        }else {
            sysUser.setCustomerId(Long.parseLong(sysUserDto.getCustomerId()));
        }
        Integer rest = sysUserService.addSysUser(sysUser);
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 修改账户信息
     *
     * @param sysUserDto
     * @return
     */
    @ApiOperation(value = "修改账户信息", notes = "角色类型为客户时，客户id必传，否则不传")
    @DynamicParameters(name = "updateSysUser", properties = {
            @DynamicParameter(name = "userId", value = "账号名", dataTypeClass = Integer.class, required = true)
            , @DynamicParameter(name = "account", value = "账号名", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "password", value = "密码", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "roleId", value = "角色id", dataTypeClass = Long.class, required = true)
            , @DynamicParameter(name = "customerId", value = "客户id", dataTypeClass = String.class, required = false)
    })
    @PutMapping("/updateSysUser")
    public RespEntity updateSysUser(@RequestBody UserDto sysUserDto) {
        logger.info("updateSysUser param " + sysUserDto.toString());
        SysUser currentSysUserInfo = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        RespEntity respEntity = authenticationService.checkAdmin(currentSysUserInfo);
        if (respEntity != null) {
            return respEntity;
        }
        //鉴别修改后的用户名，除开自己是否已经存在
        SysUser user = sysUserService.getSysUserByAccount(sysUserDto.getAccount());
        if (user != null) {
            if (!user.getUserId().equals(sysUserDto.getUserId())) {
                return new RespEntity(RespCode.USER_EXIST);
            }
        }
        SysUser sysUser = new SysUser();
        sysUser.setCreateTime(new Date().getTime());
        sysUser.setAccount(sysUserDto.getAccount());
        sysUser.setPassword(sysUserDto.getPassword());
        sysUser.setRoleId(sysUserDto.getRoleId());
        sysUser.setUpdateTime(new Date().getTime());
        sysUser.setUserId(sysUserDto.getUserId());
        if (StringUtils.isBlank(sysUserDto.getCustomerId())) {
            sysUser.setCustomerId(0L);
        }else {
            sysUser.setCustomerId(Long.parseLong(sysUserDto.getCustomerId()));
        }
        Integer rest = sysUserService.updateSysUser(sysUser);
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 删除账号信息
     *
     * @param userId
     * @return
     */
    @ApiOperation(value = "删除账号信息", notes = "当角色是客户时必传客户id,否则customerId不传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataTypeClass = Integer.class)
    })
    @DeleteMapping("/deleteSysUser/{userId}")
    public RespEntity deleteSysUser(@PathVariable("userId") Integer userId) {
        SysUser currentSysUserInfo = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        RespEntity respEntity = authenticationService.checkAdmin(currentSysUserInfo);
        if (respEntity != null) {
            return respEntity;
        }
        logger.info("deleteSysUser param " + userId);
        Integer rest = sysUserService.deleteSysUser(userId);
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     *熔断测试
     */
    @GetMapping("/timeOut")
    public String timeOut(@RequestParam int mills) {
        logger.info("[client服务-{}] [timeOut方法]收到请求,阻塞{}ms",  mills);
        try {
            Thread.sleep(mills);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.info("[client服务-{}] [timeOut]返回请求");
        return "client服务-%s 请求ok!!!";
    }

    @GetMapping("/gatewayWebFallback")
    public RespEntity gatewayWebFallback(HttpServletRequest request){
        logger.info("gatewayWebFallback param request=",  request);
        return new RespEntity(RespCode.GETWAEWARY_timeout);
    }



}
